package it.trekker.dao.ejb;

import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.security.annotation.SecurityDomain;

import it.trekker.dao.Excursion;
import it.trekker.dao.Poi;
import it.trekker.dao.IPoiDAO;

@SecurityDomain("TrekkerRealm")
@RolesAllowed("viewer")
@Stateless
@Local(IPoiDAO.class)
public class EJB3PoiDAO implements IPoiDAO {

	@PersistenceContext(unitName = "TrekkerUnit")
	protected EntityManager em;
	
	public int insert(Poi poi) {
		if(poi != null) {
			if(poi.getExcursion() != null && poi.getExcursion().getId() > 0)
				poi.setExcursion(em.merge(poi.getExcursion()));
				
			em.persist(poi);
			return (int) poi.getId();
		}
		
		return 0;
	}

	public int remove(int id) {
		Poi poi = findPoiById(id);
		
		if(poi != null) {
			em.remove(poi);
			return id;
		}
		
		return 0;
	}

	public int update(Poi poi) {
		if(poi != null) {
			if(em.merge(poi) != null)
				return (int) poi.getId();
		}
		return 0;
	}

	public Poi findPoiById(int id) {
		return em.find(Poi.class, id);
	}

	public List<Poi> findPoisByExcursion(Excursion excursion) {
		if(excursion != null) {
			excursion = em.merge(excursion);

			return em.createQuery(
					"SELECT DISTINCT (p) FROM Poi p JOIN FETCH p.location " +
							"WHERE p.excursion = :excursion"
					).setParameter("excursion", excursion).getResultList();
		}

		return null;
	}

	public List<Poi> findAllPois() {
		return em.createQuery("from Poi").getResultList();
	}

}
